package cn.hp.beauty.common.security;

import cn.hp.beauty.domain.Userinfo;
import cn.hp.beauty.service.UserinfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserinfoService userinfoService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Userinfo userinfo = userinfoService.findUserByUsername(username);

        if (userinfo == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        return new User(userinfo.getUName(), userinfo.getUPwd(), getUserAuth(userinfo.getUId()));
    }

    public List<? extends GrantedAuthority> getUserAuth(int uid) {
        String authority = userinfoService.getUserAuthority(uid);

        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
